package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping(value = "/admin/dish")
@Api(tags = "菜品相关接口")
@Slf4j
public class DishController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DishService dishService;

    @ApiOperation("新增菜品")
    @PostMapping
    public Result<String> save(@RequestBody DishDTO dishDTO){
        log.info("新增菜品",dishDTO);
        dishService.saveWithFlavor(dishDTO);

        //清除缓存数据
        String key = "dish_"+dishDTO.getCategoryId();
        clearCache(key);
        return Result.success();
    }


    @ApiOperation("菜品分页查询")
    @GetMapping(value = "/page")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO){
        log.info("菜品分页查询");
        PageResult pageResult = dishService.pageQuery(dishPageQueryDTO);
        return Result.success(pageResult);
    }


    @ApiOperation("批量删除菜品")
    @DeleteMapping
    public Result<Void> delete(@RequestParam List<Long> ids){
        log.info("批量删除菜品");
        dishService.deleteBatch(ids);

        //可能删除多个菜品，可能会影响多个套餐，可能影响多个key，所以删除所有套餐缓存数据
        clearCache("dish_*");
        return Result.success();

    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查询菜品和关联口味")
    public Result<DishVO> getById(@PathVariable Long id){
        return Result.success(dishService.getByIdWithFlavor(id));
    }

    @PutMapping
    @ApiOperation("修改菜品")
    public Result<Void> update(@RequestBody DishDTO dishDTO){
        log.info("修改菜品",dishDTO);
        dishService.updateWithFlavor(dishDTO);

        //可能影响多个套餐数据
        clearCache("dish_*");
        return Result.success();

    }

    //根据分类id查询菜品
    @ApiOperation("根据分类id查询菜品")
    @GetMapping("/list")
    public Result<List<Dish>> list(long categoryId){
        List<Dish> list =dishService.list(categoryId);
        return Result.success(list);

    }

    //清理指定缓存数据
    private void clearCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }


    //修改菜品状态
    @PostMapping(value = "/status/{status}")
    public Result<Void> startOrStop(@PathVariable Integer status,Long id){
        dishService.startOrStop(status,id);
        //一个菜品停售可能影响多个套餐数据，清空所有缓存数据
        clearCache("dish_*");
        return Result.success();
    }
}
